<template>
	<div style="width:100%;margin-left: -3%;text-align: left;height: auto;">
		<a-comment>
			<template #actions>
				<a-row>
					<a-col :span="21">
						<span style="width: auto;text-align: left;">
							<a-popover position="tl" trigger="click" style="width: 400px;height: auto;">
								<i class="iconfont iconfont-expression" style="font-size: 18px;cursor: pointer;" />
								<template #content>
									<a-tabs position="left" style="margin-left: -6%;">
										<a-tab-pane :title="item.name" v-for="(item,index) in faceList.emojiArr" 
										:key="index" style="width: 100%;min-height: 100px;max-height: 150px;overflow-y: scroll;">
											<a-space wrap align="center">
												<a-col v-for="(itemChild,indexChild) in faceList.emojiArr[index].iconArr"
												:key="indexChild" @click="addEmoji(itemChild.icon)"
												style="cursor: pointer;"
												>
													{{itemChild.icon}}
												</a-col>
											</a-space>
										</a-tab-pane>
									</a-tabs>
								</template>
							</a-popover>
						</span>
					</a-col>
					<a-col :span="3">
						<a-button type="primary" style="transform: translateX(16%);" @click="submitComment">
							<template #icon>
								<IconMessage style="cursor: pointer;" />
							</template>
							<template #default>
								评论
							</template>
						</a-button>
					</a-col>
				</a-row>
			</template>
			<template #avatar>
				<a-avatar v-if="userInfo.data">
					<img alt="avatar" 
						:src="userInfo.data.avatar" />
				</a-avatar>
				<a-avatar v-else>
					<img alt="avatar"
						src="https://p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/3ee5f13fb09879ecb5185e440cef6eb9.png~tplv-uwbnlip3yd-webp.webp" />
				</a-avatar>
			</template>
			<template #content>
				<div>
					<a-mention id="commentText" :model-value="commentContent"
					style="width: 786px;background-color: white;" type="textarea" 
					:data="mentionsList"
					:auto-size="{
					    minRows:2,
					    maxRows:5
					  }"
					/>
				</div>
			</template>
		</a-comment>
		<a-divider style="width: 838px;" />
		<a-comment v-for="(commentItem,index) in commentsList.data" :key="commentItem.cId">
			<template #avatar>
				<a-avatar>
					<img alt="avatar" :src="commentItem.avatar" />
				</a-avatar>
			</template>
			<template #content>
				{{commentItem.content}}
			</template>
			<template #actions>
				<span key="heart" @click="onLikeChange(commentItem.cId)">
					<span v-if="currentComment == commentItem.cId || isLove(commentItem.cId)">
						<IconHeartFill style="color:#f53f3f" />
					</span>
					<span v-else>
						<IconHeart />
					</span>
					{{ commentItem.love }}
				</span>
				<span key="reply">
					<span v-if="comment && currentShowComment == commentItem.cId" style="color: deepskyblue;">
						<IconMessage />回复
						<a-comment align="right">
							<template #avatar>
								<a-avatar v-if="userInfo.data">
									<img alt="avatar" 
										:src="userInfo.data.avatar" />
								</a-avatar>
								<a-avatar v-else>
									<img alt="avatar"
										src="https://p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/3ee5f13fb09879ecb5185e440cef6eb9.png~tplv-uwbnlip3yd-webp.webp" />
								</a-avatar>
							</template>
							<template #actions>
								<span style="width: auto;text-align: left;">
									<a-popover position="tl" trigger="click" style="width: 400px;height: auto;">
										<i class="iconfont iconfont-expression" style="font-size: 18px;cursor: pointer;" />
										<template #content>
											<a-tabs position="left" style="margin-left: -6%;">
												<a-tab-pane :title="item.name" v-for="(item,index) in faceList.emojiArr" 
												:key="index" style="width: 100%;min-height: 100px;max-height: 150px;overflow-y: scroll;">
													<a-space wrap align="center">
														<a-col v-for="(itemChild,indexChild) in faceList.emojiArr[index].iconArr"
														:key="indexChild" @click="addChildEmoji(itemChild.icon)"
														style="cursor: pointer;"
														>
															{{itemChild.icon}}
														</a-col>
													</a-space>
												</a-tab-pane>
											</a-tabs>
										</template>
									</a-popover>
								</span>
								<a-button key="0" type="secondary" @click="()=>{comment = !comment}"> 取消 </a-button>
								<a-button key="1" type="primary" @click="submitChildComment(commentItem.cId)"> 发送 </a-button>
							</template>
							<template #content>
								<a-mention id="childrenCommentText" :model-value="commentContent"
								style="background-color: white;" type="textarea" 
								:data="mentionsList"
								:auto-size="{
								    minRows:2,
								    maxRows:5
								  }"
								/>
							</template>
						</a-comment>
					</span>
					<span v-else @click="onComment(commentItem.cId)">
						<IconMessage />回复
						{{commentItem.children.length}}
					</span>
				</span>
				<span v-if="commentItem.uId == currentuId"
				style="display: inline-block;width: 683px;text-align: right;margin-left: 5px;height: 16px;
				">
					<span style="cursor: pointer;" @click="deleteMyComment(commentItem.cId)">删除</span>
				</span>
			</template>
			<template #datetime>
				<span>发布于：{{commentItem.publishTime}}</span>
				<span style="color: #272E3B;display: inline-block;width: 200px;">
					&nbsp;({{moment(commentItem.publishTime).fromNow()}})
				</span>
			</template>
			<template #author>
				<a-row :wrap="false">
					<a-col :span="12">
						{{commentItem.nickName}}
					</a-col>
					<a-col :span="12" style="text-align: right;">
						{{index+2}}楼
					</a-col>
				</a-row>
			</template>
			<a-divider style="transform: translateX(-7%);padding-right: 50px;"/>
			<!--嵌套评论-->
				<a-comment v-for="(child,cIndex) in commentItem.children" :key="child.cId">
					<template #avatar>
						<a-avatar>
							<img alt="avatar" :src="child.avatar" />
						</a-avatar>
					</template>
					<template #content>
						{{child.content}}
					</template>
					<template #actions>
						<span key="heart" @click="onLikeChange(child.cId)">
							<span v-if="currentComment == child.cId || isLove(child.cId)">
								<IconHeartFill style="color:#f53f3f" />
							</span>
							<span v-else>
								<IconHeart />
							</span>
							{{ child.love }}
						</span>
						<span v-if="child.uId == currentuId"
						style="display: inline-block;width: 693px;text-align: right;margin-left: 5px;height: 16px;
						">
							<span style="cursor: pointer;" @click="deleteMyChildComment(commentItem.cId,child.cId)">
								删除
							</span>
						</span>
					</template>
					<template #datetime>
						<span>发布于：{{child.publishTime}}</span>
						<span style="color: #272E3B;">&nbsp;({{moment(child.publishTime).fromNow()}})</span>
					</template>
					<template #author>
						<a-row :wrap="false">
							<a-col :span="12">
								{{child.nickName}}
							</a-col>
							<a-col :span="12" style="text-align: right;">
							</a-col>
						</a-row>
					</template>
					<a-divider style="transform: translateX(-7%);padding-right: 50px;"/>
				</a-comment>
		</a-comment>
		<a-row :wrap="false">
			<a-col :span="20" style="text-align: right;">
				<a-pagination id="pageSplit" :total="commentsList.total" show-total show-jumper show-page-size 
				:page-size-options="[1,10]" @change="changePageList" @page-size-change="changeSizeList" 
				v-if="commentsList.total > 0"/>
				<a-result :status="null" v-else-if="commentsList.total == 0">
					<template #icon>
						<IconFaceFrownFill style="color: gray;"/>
					</template>
					<template #title>该评测还没有人评论</template>
				</a-result>
			</a-col>
		</a-row>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive,
		getCurrentInstance,
		onMounted,
		inject,
		watch,
		nextTick
	} from 'vue';

	import faceList from '@/components/modelEvaluating/emoji/emojiArr.js';
	import indexApi from '@/module/modelEvaluating/api/index.js';
	import userApi from '@/module/user/api/index.js';
	import { Modal } from '@arco-design/web-vue';
	import jwt_decode from 'jwt-decode';
	import moment from "moment";
	import 'moment/dist/locale/zh-cn'
	moment.locale('zh-cn');

	let {
		proxy
	} = getCurrentInstance();

	const props = defineProps({
		commentsList: Object,
		mentionsList:Array,
		currentPage:Number,
		currentPageSize:Number
	});

	const emit = defineEmits();

	let currentLikeList = ref([]);
	let like = ref(false);

	let comment = ref(false);
	let currentComment = ref();
	let currentShowComment = ref();

	let actionList = reactive({});
	
	let commentContent = ref();
	let childrenCommentContent = ref();
	
	let myCommentStatus = reactive({});
	let myChildCommentStatus = reactive({});
	let myLoveStatus = reactive({});
	let articleId = ref();
	let userInfo = reactive({});
	let currentuId;
	if(sessionStorage.getItem('token')){
		currentuId = jwt_decode(sessionStorage.getItem("token")).uid;
	}
	
	async function deleteMyComment(cId){
		Modal.open({
		        title: '警告',
		        content: '确定要删除该评论吗?',
				async onOk(){
					let myDeleteCommentStatus = reactive({});
					let commentDto = {
						aId: articleId.value,
						parentId: '0',
						cId: cId
					};
					console.log('commentDto',commentDto);
					myDeleteCommentStatus.resp = await indexApi.deleteCommentByCid(commentDto);
					console.log('myDeleteCommentStatus.resp',myDeleteCommentStatus.resp);
					if(myDeleteCommentStatus.resp.flag == true){
						proxy.$message.success('删除评论成功');
						nextTick(()=>{
							emit('refrushParnentComment',true);
						});
					}
					else if(myDeleteCommentStatus.resp.flag == false){
						proxy.$message.error('删除评论失败');
					}
				}
		      });
	}
	
	async function deleteMyChildComment(parentId,cId){
		Modal.open({
		        title: '警告',
		        content: '确定要删除该评论吗?',
				async onOk(){
					let myDeleteCommentStatus = reactive({});
					let commentDto = {
						aId: articleId.value,
						cId: cId,
						parentId: parentId
					};
					console.log('commentDto',commentDto);
					myDeleteCommentStatus.resp = await indexApi.deleteChildCommentByCid(commentDto);
					console.log('myDeleteCommentStatus.resp',myDeleteCommentStatus.resp);
					if(myDeleteCommentStatus.resp.flag == true){
						proxy.$message.success('删除评论成功');
						nextTick(()=>{
							emit('refrushParnentComment',true);
						});
					}
					else if(myDeleteCommentStatus.resp.flag == false){
						proxy.$message.error('删除评论失败');
					}
				}
		      });
	}
	
	function isLove(cId){
		if(sessionStorage.getItem("token")){
			if(actionList.data && actionList.data[0] != '你还没有任何点赞'){
				return actionList.data.indexOf(cId) != -1 ? true : false;
			}
		}
	}
	
	if(inject('getAid')){
		articleId = inject('getAid');
	}
	async function submitChildComment(parentId){
		if(sessionStorage.getItem('token')){
			let commentText = document.querySelector('#childrenCommentText .arco-textarea');
			console.log('myComment',commentText.value);
			console.log('parentId',parentId);
			console.log('articleId',articleId.value);
			if(sessionStorage.getItem("token") && commentText.value.trim() != ''){
				let commentDto = {
					aId: articleId.value,
					uId: jwt_decode(sessionStorage.getItem("token")).uid,
					parentId: parentId,
					content: commentText.value
				};
				console.log('commentDto',commentDto);
				myChildCommentStatus.resp = await indexApi.submitComment(commentDto);
				console.log('myChildCommentStatus.resp',myChildCommentStatus.resp);
				if(myChildCommentStatus.resp.flag == true){
					proxy.$message.success('评论成功');
					commentText.value = '';
					comment.value = false;
					emit('refrushParnentComment',true);
				}
			}
			else if(sessionStorage.getItem("token") && commentText.value.trim() == ''){
				proxy.$message.error('请输入内容');
			}
			else{
				proxy.$message.error('请先登录');
			}
		}
		else{
			proxy.$message.error('请先登录');
		}
	}
	
	async function submitComment(){
		if(sessionStorage.getItem('token')){
			let commentText = document.querySelector('#commentText .arco-textarea');
			console.log('myComment',commentText.value);
			console.log('articleId',articleId.value);
			if(sessionStorage.getItem("token") && commentText.value.trim() != ''){
				let commentDto = {
					aId: articleId.value,
					uId: jwt_decode(sessionStorage.getItem("token")).uid,
					parentId: '0',
					content: commentText.value
				};
				console.log('commentDto',commentDto);
				myCommentStatus.resp = await indexApi.submitComment(commentDto);
				console.log('myCommentStatus.resp',myCommentStatus.resp);
				if(myCommentStatus.resp.flag == true){
					proxy.$message.success('评论成功');
					commentText.value = '';
					emit('refrushParnentComment',true);
				}
			}
			else if(sessionStorage.getItem("token") && commentText.value.trim() == ''){
				proxy.$message.error('请输入内容');
			}
			else{
				proxy.$message.error('请先登录');
			}
		}
		else{
			proxy.$message.error('请先登录');
		}
	}

	async function onLikeChange(index) {
		if(sessionStorage.getItem('token')){
			if(actionList.data[0] != '你还没有任何点赞'){
				//该条评论已经点赞
				if(actionList.data.indexOf(index) != -1){
					//取消点赞
					myLoveStatus.resp = await indexApi.cancelLove(index,jwt_decode(sessionStorage.getItem("token")).uid);
					console.log('myCancelLoveStatus.resp',myLoveStatus.resp);
					if(myLoveStatus.resp.flag == true){
						proxy.$message.success('已取消点赞');
						currentComment.value = ''
						emit('refrushParnentComment',true);
						nextTick(()=>{
							loadingActionList();
						});
					}
				}
				//该条评论没有点赞
				else{
					//点赞
					currentComment.value = index;
					console.log('currentComment',currentComment.value);
					myLoveStatus.resp = await indexApi.loveComment(index,jwt_decode(sessionStorage.getItem("token")).uid);
					console.log('myAddLoveStatus.resp',myLoveStatus.resp);
					if(myLoveStatus.resp.flag == true){
						proxy.$message.success('点赞成功');
						emit('refrushParnentComment',true);
						nextTick(()=>{
							loadingActionList();
						});
					}
				}
			}
			else if(actionList.data[0] == '你还没有任何点赞'){
				//点赞
				currentComment.value = index;
				console.log('currentComment',currentComment.value);
				myLoveStatus.resp = await indexApi.loveComment(index,jwt_decode(sessionStorage.getItem("token")).uid);
				console.log('myAddLoveStatus.resp',myLoveStatus.resp);
				if(myLoveStatus.resp.flag == true){
					proxy.$message.success('点赞成功');
					emit('refrushParnentComment',true);
					nextTick(()=>{
						loadingActionList();
					});
				}
			}
		}
		else{
			proxy.$message.error('请先登录');
		}
	}

	function onComment(index) {
		comment.value = !comment.value;
		currentShowComment.value = index;
	}
	
	function addChildEmoji(val){
		//获取文本框的节点
		let commentText = document.querySelector('#childrenCommentText .arco-textarea');
		//获取光标
		let cursor = commentText.selectionStart;
		//设置文本内容
		commentText.setRangeText(val);
		//移动光标并聚焦
		commentText.selectionStart = cursor + 2;
		commentText.focus();
		//使文本框的内容等于当前值
		childrenCommentContent.value = childrenCommentContent.value;
	}
	
	function addEmoji(val){
		//获取文本框的节点
		let commentText = document.querySelector('#commentText .arco-textarea');
		//获取光标
		let cursor = commentText.selectionStart;
		//设置文本内容
		commentText.setRangeText(val);
		//移动光标并聚焦
		commentText.selectionStart = cursor + 2;
		commentText.focus();
		//使文本框的内容等于当前值
		commentContent.value = commentContent.value;
	}
	
	function changePageList(number){
		console.log('当前页数:',number);
		emit('PageChange',number);
	}
	
	function changeSizeList(number){
		console.log('当前条数:',number);
		emit('SizeChange',number);
	}

	async function loadingActionList() {
		if(sessionStorage.getItem("token")){
			actionList.resp = await indexApi.getActionList(jwt_decode(sessionStorage.getItem("token")).uid);
			actionList.data = actionList.resp.data;
			console.log('actionList.resp', actionList.resp);
			console.log('actionList', actionList.data);
			return actionList;
		}
	}
	
	async function loadingUserInfo(){
		if(sessionStorage.getItem("token")){
			userInfo.detail = jwt_decode(sessionStorage.getItem("token"));
			console.log('userInfo',userInfo.detail.uid);
			if(userInfo.detail.uid != undefined || userInfo.detail.uid != null || userInfo.detail.uid != ''){
				userInfo.resp = await userApi.getUserInfo(userInfo.detail.uid);
				userInfo.data = userInfo.resp.data;
				console.log('userInfo',userInfo.data);
			}
		}
	}

	onMounted(() => {
		loadingActionList();
		loadingUserInfo();
		console.log('commentsList',props.commentsList)
	});
</script>

<style lang="less" scoped>
</style>
